import base64
import os
import signal
import sys

from PIL import Image, ImageGrab
from tkinter import filedialog

from src.log import DEBUG, SCRIPTP


FONT_FILE_NAME = 'AlimamaFangYuanTiVF-Thin-2.ttf'
FONT_FAMILY = '阿里妈妈方圆体 VF Medium'


def shutdown():
    """关闭应用"""
    pid = os.getpid()
    os.kill(pid, signal.SIGTERM)


# 调整颜色亮度的工具函数
def adjust_color(color_hex):
    """调整十六进制颜色的亮度"""
    # 移除#号
    color_hex = color_hex.lstrip('#')
    
    # 转换为RGB值
    r = int(color_hex[0:2], 16)
    g = int(color_hex[2:4], 16)
    b = int(color_hex[4:6], 16)
    
    # 调整亮度
    factor = 0.8
    r = int(r * factor)
    g = int(g * factor)
    b = int(b * factor)
    
    # 确保值在0-255范围内
    r = max(0, min(r, 255))
    g = max(0, min(g, 255))
    b = max(0, min(b, 255))
    
    # 转换回十六进制
    return f'#{r:02x}{g:02x}{b:02x}'


# 创建圆角矩形路径的工具函数
def create_rounded_rectangle_path(rect, radius):
    """创建圆角矩形路径"""
    from PySide2.QtGui import QPainterPath
    path = QPainterPath()
    path.addRoundedRect(rect, radius, radius)
    return path


def png2ico(png_path, ico_path, sizes=[(16, 16), (32, 32), (48, 48), (256, 256)]):
    """
    将PNG图像转换为ICO格式。
    
    :param png_path: PNG图像的路径。
    :param ico_path: 要保存的ICO文件的路径。
    :param sizes: 要生成的ICO图标的大小列表。
    """
    base_image = Image.open(png_path)
    base_image.load()
    background = Image.new("RGB", base_image.size, (255, 255, 255))
    background.paste(base_image, (0, 0))
    
    ico = Image.new("RGBA", (max(sizes)[0], max(sizes)[0]))
    for size in sizes:
        resized_image = base_image.copy().resize(size, Image.LANCZOS)
        ico.paste(resized_image, ((max(sizes)[0] - size[0]) // 2, (max(sizes)[0] - size[1]) // 2))
    
    ico.save(ico_path, format='ICO', sizes=sizes)


def get_screenshoot():
    return ImageGrab.grab()


def cut_image(box):
    return ImageGrab.grab(bbox=box)


# 导入cefpython3模块，如果未安装请先运行: pip install cefpython3
try:
    from cefpython3 import cefpython as cef
except ImportError:
    print(f'cef python 模块未安装, 请先安装cefpython3模块: pip install cefpython3')

# 初始化CEF
def init_cef():
    try:
        if not cef.__version__:
            raise Exception("CEF Python is not installed")
        sys.excepthook = cef.ExceptHook
        if DEBUG:
            settings = {}
        else:
            if not SCRIPTP.joinpath('cefpython3/subprocess.exe').exists():
                print(f'cefpython3/subprocess.exe 不存在')
            settings = {
                "locales_dir_path": str(SCRIPTP.joinpath('cefpython3/locales')),
                "resources_dir_path": str(SCRIPTP.joinpath('cefpython3')),
                "browser_subprocess_path": str(SCRIPTP.joinpath('cefpython3/subprocess.exe'))
            }
        cef.Initialize(settings=settings, switches={
            "disable-gpu": "",
            "disable-gpu-compositing": "",
            "enable-media-stream": 1
        })
        # "enable-system-flash", "1");  //flash
        # "enable-speech-input", "1");  //语音输入
        print(f'cef version: {str(cef.__version__)}')
    except Exception as e:
        print(f'cef python 加载失败: {str(e)}')

# 确保在程序退出时关闭CEF
def shutdown_cef():
    cef.Shutdown()

def createBrowserSync(settings, window_info, url, title):
    browser = cef.CreateBrowserSync(settings=settings, window_info=window_info, url=url, window_title=title)
    return browser

 # 初始化CEF
init_cef()


class TInteractObj(object):

    def __init__(self, ui=None):
        super().__init__()
        self.ui = ui
    
    def show(self):
        print("triggle show")
        try:
            self.ui.window.attributes('-alpha', 1)
        except Exception as e:
            print(f'显示窗口异常: {str(e)}')
    
    def choosePicture(self, callback):
        print("triggle choosePicture")
        try:
            # 打开文件对话框
            file_path = filedialog.askopenfilename(
                parent=self.ui.window,
                title="选择图片",
                filetypes=[("Images", "*.png *.jpg *.bmp")]
            )
            if file_path:
                # 发送文件数据给 JavaScript
                with open(file_path, "rb") as f:
                    file_data = f.read()
                    base64_data = base64.b64encode(file_data).decode("utf-8")
                callback.Call({
                    "path": file_path,
                    "base64": base64_data
                })
        except Exception as e:
            print(f'选择文件异常: {str(e)}')

    def choosePictures(self, callback):
        print("triggle choosePicture")
        try:
            # 打开文件对话框
            files_path = filedialog.askopenfilenames(
                parent=self.ui.window,
                title="选择图片",
                filetypes=[("Images", "*.png *.jpg *.bmp")]
            )
            if files_path:
                images = []
                for p in files_path:
                    with open(p, "rb") as f:
                        file_data = f.read()
                        base64_data = base64.b64encode(file_data).decode("utf-8")
                        images.append({
                            "path": p,
                            "base64": base64_data
                        })
                callback.Call({
                    "pictures": images
                })
        except Exception as e:
            print(f'选择文件异常: {str(e)}')

    def chooseFile(self, filetypes='[("所有文件", "*.*")]', callback=None):
        print("triggle chooseFile")
        try:
            filetypes = eval(filetypes)
            # 打开文件对话框
            file_path = filedialog.askopenfilename(
                parent=self.ui.window,
                title="选择文件",
                filetypes=filetypes
            )
            if file_path and callback:
                callback.Call({
                    "path": file_path
                })
        except Exception as e:
            print(f'选择文件异常: {str(e)}')

    def chooseFiles(self, filetypes='[("所有文件", "*.*")]', callback=None):
        print("triggle chooseFiles")
        try:
            filetypes = eval(filetypes)
            # 打开文件对话框
            file_paths = filedialog.askopenfilenames(
                parent=self.ui.window,
                title="选择文件",
                filetypes=filetypes
            )
            if file_paths and callback:
                callback.Call({
                    "paths": file_paths
                })
        except Exception as e:
            print(f'选择文件异常: {str(e)}')

    def chooseDir(self, callback):
        print("triggle chooseDir")
        try:
            # 打开文件对话框
            dir_path = filedialog.askdirectory(
                parent=self.ui.window,
                title="选择文件夹"
            )
            if dir_path:
                # 发送文件数据给 JavaScript
                callback.Call({
                    "path": dir_path
                })
        except Exception as e:
            print(f'选择文件夹异常: {str(e)}')
    
    def maxWindow(self):
        print("triggle maxWindow")
        self.ui.max()

    def normalWindow(self):
        print("triggle normalWindow")
        self.ui.normal()
    
    def hideWindow(self):
        print("triggle hideWindow")
        try:
            self.ui.hide()
        except Exception as e:
            print(f'隐藏窗口异常: {str(e)}')

    def closeWindow(self):
        print("triggle closeWindow")
        try:
            self.ui.window.attributes('-alpha', 0)
            if self.ui.window.parent:
                self.ui.window.parent.withdraw()
            self.ui.webview.LoadUrl('http://127.0.0.1:9505/blank')
        except Exception as e:
            print(f'关闭窗口异常: {str(e)}')
    
    def exitApp(self):
        print("triggle exitApp")
        try:
            self.ui.close()
        except Exception as e:
            print(f'退出程序异常: {str(e)}')

